/**
 * <b>项目名：</b>monitor<br/>
 * <b>包名：</b>org.monitor.main<br/>
 * <b>文件名：</b>Client.java<br/>
 * <b>版本信息：</b> @version 1.0.0<br/>
 * <b>日期：</b>2013-6-8-下午6:10:44<br/>
 * <b>Copyright (c)</b> 2013魅族公司-版权所有<br/>
 *
 */

package org.monitor.main;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.monitor.common.Common;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerList;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * <b>类名称：</b>MClient<br/>
 * <b>类描述：</b>
 * 
 * <pre>
 </pre>
 * 
 * <br/>
 * <b>创建人：</b>张军强<br/>
 * <b>修改人：</b>张军强<br/>
 * <b>修改时间：</b>2013-6-8 下午6:10:44<br/>
 * <b>修改备注：</b><br/>
 * 
 * @version 1.0.0<br/>
 */

public class MClient implements IService {

	private static String registerKey = new String(); // 须要设置合适的初值。

	private static String serverUrl = null;

	private static Logger logger = Logger.getLogger(MClient.class);

	private static MClient _instance = new MClient();

	private static boolean isRunning = false;

	private static String assertjs;

	public static Scheduler scheduler;
	

	public static String getAssertjs() {
		return assertjs;
	}

	public static Scheduler getScheduler() {
		return scheduler;
	}

	public static void setScheduler(Scheduler scheduler) {
		MClient.scheduler = scheduler;
	}

	private MClient() {
	}

	/**
	 * 生成新的registerKey的方法
	 * 
	 * @return
	 */
	public static String getKey() {

		Random r = new Random();
		r.setSeed(r.nextLong());
		String key = new String(r.nextInt(10000000) + "");
		registerKey=key;
		return key;
	}

	public static MClient getInstance() {
		return _instance;
	}

	private static void addJob(JSONObject json) {

	}

	private static void submitData(JSONObject data) {

	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see org.monitor.main.IService#startService(int)
	 */

	public void startService(Properties conf) {
		// TODO Auto-generated method stub

		if (!isRunning) {
			try {
				// serverUrl = conf.get("server").toString();
				scheduler = StdSchedulerFactory.getDefaultScheduler();
				scheduler.start();
				Common.registerHeartBeat();
				// sdl.shutdown();
			} 
			catch (SchedulerException e) {
				e.printStackTrace();
			}
		
			//InputStream resource = this.getClass().getResourceAsStream("/util.js");
			try {
				assertjs = Common.getFile(Main.confPath+"/conf/util.js");
			} catch (Exception e) {
				logger.error("startService:\t"+ e.getMessage());
			}
			

			Server server = new Server(Integer.valueOf(conf.get("client.port").toString()));
			
			HandlerList handlers = new HandlerList();
			handlers.setHandlers(new Handler[] { new CilentHandler(), new DefaultHandler() });
			server.setHandler(handlers);
			try {
				// registerService();
				server.start();
				// server.join();
				isRunning = true;

				logger.info("服务成功启动");
			} catch (Exception e) {
				logger.error("服务启动出错");
			}
		}

	}

	public static class CilentHandler extends AbstractHandler {
		

		


		public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
			
			if(!Common.checkSign(request, response)){
				return;
			}
			response.setContentType("text/html;charset=UTF-8");
			String action = request.getParameter("action") == null ? "" : request.getParameter("action");

			if (action.equalsIgnoreCase("updateComConf")) {
				updateCommonConfig(request, response);
			} else if (action.equalsIgnoreCase("updatePrivConf")) {
				updatePrivConf(request, response);
			} else if (action.equalsIgnoreCase("execCmd")) {
				execCmd(request, response);
			} else if (action.equalsIgnoreCase("updateFunc")) {
				updateFunc(request, response);
			} else {
				response.getWriter().write("undefined service");
			}
			
			response.getWriter().flush();
			response.setStatus(HttpServletResponse.SC_OK);
			((Request) request).setHandled(true);

			JSONObject obj = new JSONObject();

			// TODO 完成这个

			// String cmd = request.getParameter("cmd");
			//
			// try {
			//
			// response.getWriter().write(Common.execCmd(cmd, 0));
			// response.setStatus(HttpServletResponse.SC_OK);
			// ((Request) request).setHandled(true);
			//
			// } catch (Exception e) {
			// response.getWriter().write(e.getLocalizedMessage());
			// response.setStatus(HttpServletResponse.SC_OK);
			// ((Request) request).setHandled(true);
			//
			// }
			//
			// }
		}
	}

	/**
	 * <b>创建人：</b>张军强<br/>
	 * main<br/>
	 * <b>方法描述：</b> <br/>
	 * 
	 * @param args
	 *            void
	 * @exception
	 * @since 1.0.0
	 */

	public static void main(String[] args) {
		for (int i = 0; i < 10; i++)
			System.out.println(getKey());

	}

	/**
	 * <b>创建人：</b>张军强<br/>
	 * updatePrivConf<br/>
	 * <b>方法描述：</b> <br/>
	 * 
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */

	public static void updatePrivConf(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

	}

	/**
	 * <b>创建人：</b>张军强<br/>
	 * execCmd<br/>
	 * <b>方法描述：</b> <br/>
	 * 
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */

	public static void execCmd(HttpServletRequest request, HttpServletResponse response) {
		String param = request.getParameter("param");

		Map map = JSONObject.parseObject(param, Map.class);
		
		
		String cmd=map.get("cmd") == null ? "" : map.get("cmd").toString();
		
		String termIp=map.get("termIp")==null?"":map.get("termIp").toString();
		
		String forbid=Main.getConfig().get("cmd.forbid")==null?"":Main.getConfig().get("cmd.forbid").toString();
		
		String ipallow=Main.getConfig().get("ip.allow")==null?"":Main.getConfig().get("ip.allow").toString();
		
		
		String[] forbids = forbid.split("\\|");
		
		boolean canRun=true;
		
		
//		if(ipallow=="") {
//			canRun=true;
//		   
//		} else{
//			
//			if(ipallow.indexOf(termIp)!=-1) {
//				canRun=true;
//			}
//			
//		}
		
	
		String retStr = null;
		try {
			if(canRun) {
				retStr = Common.execCmd(map.get("cmd") == null ? "" : map.get("cmd").toString(), map.get("lines") == null ? 0 : Integer.valueOf(map.get("lines").toString()));
			} else {
				retStr="无权执行命令";
			}
			response.getWriter().write(retStr);
			logger.error("cmd:\t"+ map.get("cmd").toString());
		} catch (Exception e) {
			logger.error("execCmd:\t"+e.getMessage());
		}
		
		

	}

	/**
	 * <b>创建人：</b>张军强<br/>
	 * updateConfig<br/>
	 * <b>方法描述：</b> <br/>
	 * 
	 * @param request
	 * @param response
	 *            void
	 * @exception
	 * @since 1.0.0
	 */

	public static void updateCommonConfig(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * @param request
	 * @param response
	 */
	public static void updateFunc(HttpServletRequest request, HttpServletResponse response) {
		String param = request.getParameter("param");
		JSONObject jsonObject = JSONObject.parseObject(param);
		assertjs = (String) jsonObject.get("assertjs");
	}
	
	public static String getRegisterKey(){
		return registerKey;
	}
}
